﻿using System;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;


namespace Wayloop.Web.Mvc
{
    public class RestfulHttpExceptionModule : IHttpModule
    {
        /// <summary>
        /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
        /// </summary>
        public void Dispose()
        {
        }


        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            context.Error += OnApplicationError;
        }


        private void OnApplicationError(object sender, EventArgs e)
        {
            var application = (HttpApplication) sender;
            string statusCode = "";

            var exception = application.Context.Error;
            if (exception is HttpException) {
                statusCode = ((HttpException) exception).GetHttpCode().ToString();
            }

            string redirectUrl = GetRedirectUrlFromCustomErrorSection(statusCode);
            if (String.IsNullOrEmpty(redirectUrl)) {
                return;
            }

            application.Response.TrySkipIisCustomErrors = true;
            application.Server.ClearError();
            application.Server.TransferRequest(redirectUrl);
        }


        private string GetRedirectUrlFromCustomErrorSection(string statusCode)
        {
            CustomErrorsSection section = GetCustomErrorsSection();
            if (ShouldUseCustomErrors(section)) {
                if (section.Errors.AllKeys.Contains(statusCode)) {
                    return section.Errors[statusCode].Redirect;
                }

                return section.DefaultRedirect;
            }

            return null;
        }


        private bool ShouldUseCustomErrors(CustomErrorsSection section)
        {
            bool isRemoteRequest = !HttpContext.Current.Request.IsLocal;

            switch (section.Mode) {
                case CustomErrorsMode.On:
                    return true;

                case CustomErrorsMode.RemoteOnly:
                    return isRemoteRequest;
            }

            return false;
        }


        private CustomErrorsSection GetCustomErrorsSection()
        {
            return ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
        }
    }
}